package com.maiworld.api.controller;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.maiworld.content.service.ArticleService;
import com.maiworld.content.service.CommentService;
import com.maiworld.pojo.Comment;
import com.maiworld.pojo.News;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import wxutils.Constant;

@RestController
@RequestMapping("/v1/examination")
public class ExaminationController {

	@Reference
	private ArticleService articleService;
	
	@Reference
	private CommentService commentService;
	
	/**
	 * 科目二 主界面详情
	 * @param status
	 * @param openid
	 * @param sessionkey
	 * @param subject
	 * @return
	 */
	@RequestMapping(value = "/subject2main",method =RequestMethod.GET)
	public Map<String,Object> subject2main(
		@RequestParam("status") String status,
		@RequestParam("openid") String openid,
		@RequestParam("session_key") String sessionkey,
		@RequestParam("subject") String subject
	) {
		Map<String,Object> result = new HashMap<String,Object>();
		System.out.println(status);
		//获取基础视频
		List<News> basics = new ArrayList<News>();
		basics = articleService.selectByClassIdLimit(5L, status, 0, 4);
		Map<String,Object> basicsRes = new HashMap<String,Object>();
		basicsRes.put("classId", 5);
		if(basics.isEmpty()) {
			basicsRes.put("data",null);
		}else {
			basicsRes.put("data",basics);
		}
		result.put("basics", basicsRes);
		//获取考试项目视频
		List<News> project = new ArrayList<News>();
		project = articleService.selectByClassIdLimit(6L, status, 0, 10);
		Map<String,Object> projectRes = new HashMap<String,Object>();
		projectRes.put("classId", 6);
		if(project.isEmpty()) {
			projectRes.put("data",null);
		}else {
			projectRes.put("data",project);
		}
		result.put("project", projectRes);
		
		//获取考友小视频
		List<News> studentVideo = new ArrayList<News>();
		studentVideo = articleService.selectByClassIdLimit(7L, status, 0, 5);
		Map<String,Object> studentVideoRes = new HashMap<String,Object>();
		studentVideoRes.put("classId", 7);
		if(studentVideo.isEmpty()) {
			studentVideoRes.put("data",null);
		}else {
			studentVideoRes.put("data",studentVideo);
		}
		result.put("studentVideo", studentVideoRes);
				
		
		result.put("statusCode", 200);
		result.put("message", "成功");
		return result;
	}
	/**
	 * 科目三   主界面详情
	 * @param status
	 * @param openid
	 * @param sessionkey
	 * @param subject
	 * @return
	 */
	@RequestMapping(value = "/subject3main",method =RequestMethod.GET)
	public Map<String,Object> subject3main(
		@RequestParam("status") String status,
		@RequestParam("openid") String openid,
		@RequestParam("session_key") String sessionkey,
		@RequestParam("subject") String subject
	) {
		Map<String,Object> result = new HashMap<String,Object>();
		System.out.println(status);
		//获取考试项目视频
		List<News> project = new ArrayList<News>();
		project = articleService.selectByClassIdLimit(19L, status, 0, 10);
		Map<String,Object> projectRes = new HashMap<String,Object>();
		projectRes.put("classId", 19);
		if(project.isEmpty()) {
			projectRes.put("data",null);
		}else {
			projectRes.put("data",project);
		}
		result.put("project", projectRes);
		
		//获取考友小视频
		List<News> studentVideo = new ArrayList<News>();
		studentVideo = articleService.selectByClassIdLimit(20L, status, 0, 5);
		Map<String,Object> studentVideoRes = new HashMap<String,Object>();
		studentVideoRes.put("classId", 20);
		if(studentVideo.isEmpty()) {
			studentVideoRes.put("data",null);
		}else {
			studentVideoRes.put("data",studentVideo);
		}
		result.put("studentVideo", studentVideoRes);
				
		
		result.put("statusCode", 200);
		result.put("message", "成功");
		return result;
	}
	
	@RequestMapping(value = "/newsList",method =RequestMethod.GET)
	public Map<String,Object> newsListByClassId(
			@RequestParam("status") String status,
			@RequestParam("openid") String openid,
			@RequestParam("session_key") String sessionkey,
			@RequestParam("subject") String subject,
			@RequestParam("classId") String classId,
			@RequestParam("start") String start,
			@RequestParam("pageSize") String pageSize
		) {
			Map<String,Object> result = new HashMap<String,Object>();
			System.out.println(status);
			//获取文章列表
			List<News> list = new ArrayList<News>();
			list = articleService.selectByClassIdLimit(Long.parseLong(classId), status, Integer.parseInt(start), Integer.parseInt(pageSize));

			if(list.isEmpty()) {
				result.put("datalist",null);
			}else {
				result.put("datalist",list);
			}
			result.put("statusCode", 200);
			result.put("message", "成功");
			return result;
		}
	
	
	@RequestMapping(value = "/article",method =RequestMethod.GET)
	public Map<String,Object> newsById(
			@RequestParam("status") String status,
			@RequestParam("openid") String openid,
			@RequestParam("session_key") String sessionkey,
			@RequestParam("subject") String subject,
			@RequestParam("id") Long id
		) {
			Map<String,Object> result = new HashMap<String,Object>();
			System.out.println(status);
			
			//获取单个文章
			News news = articleService.selectById(id, status);
			News newss = new News();
			Integer bnum = Integer.parseInt(news.getBrowseNum()) + 1;
			newss.setBrowseNum(bnum.toString());
			newss.setId(news.getId());
			articleService.saveArticle(newss);
			result.put("data", news);
			//获取评论列表
			List<Comment> commentList = new ArrayList<Comment>();
			Comment comment = new Comment();
			comment.setAid(id);
			comment.setStatus(status);
			commentList = commentService.selectCommmentsByAid(comment);
			if(commentList.isEmpty()) {
				result.put("comments",null);
			}else {
				result.put("comments",commentList);
			}
			result.put("statusCode", 200);
			result.put("message", "成功");
			return result;
		}
	
	@RequestMapping(value = "/addComment",method =RequestMethod.POST)
	public Map<String,Object> addComment(
			@RequestBody Map<String,String> params
		) {
			Map<String,Object> result = new HashMap<String,Object>();
//			System.out.println(params);
			Comment comment = new Comment();
			comment.setUid(Long.parseLong(params.get("uid")));
			comment.setAid(Long.parseLong(params.get("aid")));
			comment.setAvator(params.get("avator"));
			comment.setName(params.get("name"));
			comment.setContent(params.get("content"));
			comment.setCreated(new Date());
			comment.setStatus(params.get("status"));
			System.out.println(comment);
			String urlsec = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constant.appid+"&secret="+Constant.appsecret;
			String httpResStr = httpGet(urlsec);
			
			//将传递过来的json串转化为JSONObject
			JSONObject jsonObject = JSONObject.parseObject(httpResStr);
			String accessToken= (String)jsonObject.get("access_token");
//			System.out.println(accessToken);
			
			String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+accessToken;
//			System.out.println(url);
			String httpPostStr = httpPost(url,comment.getContent(),accessToken);
			
//			System.out.println(httpPostStr);
			JSONObject jsonObject2 = JSONObject.parseObject(httpPostStr);
			Integer errcode= (Integer)jsonObject2.get("errcode");
			
			if(errcode == 0) {
				//添加评论
				Integer id = commentService.addComment(comment);
//				System.out.println(id);
				Comment resCom = commentService.selectCommentById(Long.parseLong(id.toString()),params.get("status"));				
				
				News news = articleService.selectById(comment.getAid(), comment.getStatus());
				Integer CommentsNum = Integer.parseInt(news.getCommentsNum()) + 1;
				news.setCommentsNum(CommentsNum.toString());
				articleService.saveArticle(news);
						
				result.put("comment", resCom);	
				result.put("statusCode", 200);
				result.put("message", "成功");
			}else {
				result.put("statusCode", 400);
				result.put("message", "内容敏感！");
			}



			return result;
		}
	
	@RequestMapping(value = "/getcode",method =RequestMethod.POST)
	public String getcode(
			@RequestBody Map<String,String> params
		) {
			System.out.println(params);
			String path = params.get("path");
			String scene = params.get("scene");
			String width = params.get("width");
			String urlsec = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constant.appid+"&secret="+Constant.appsecret;
			String httpResStr = httpGet(urlsec);
			
			//将传递过来的json串转化为JSONObject
			JSONObject jsonObject = JSONObject.parseObject(httpResStr);
			String accessToken= (String)jsonObject.get("access_token");
//			System.out.println(accessToken);
			
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
//			System.out.println(url);

			PrintWriter out = null;
			String result = "";
			InputStream inputStream=null;
			//请求数据，自行拼接
			String param="{ \"scene\":\""+scene +"\" ,\"page\":\""+path+"\",\"width\":"+width+"}";
	        try {
				URL realUrl = new URL(url);
				// 打开和URL之间的连接
				URLConnection conn = realUrl.openConnection();
				// 设置通用的请求属性
//				conn.setRequestProperty("accept", "*/*");
//				conn.setRequestProperty("connection", "Keep-Alive");
//				conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//				conn.setCharacterEncoding("gbk");
				conn.setRequestProperty("Content-Type", "application/json;charset-gbk");
				conn.setRequestProperty("responseType", "arraybuffer");
				
				// 发送POST请求必须设置如下两行
				conn.setDoOutput(true);
				conn.setDoInput(true);
				// 获取URLConnection对象对应的输出流
				out = new PrintWriter(conn.getOutputStream());
				// 发送请求参数
				out.print(param);
				// flush输出流的缓冲
				out.flush();     
				//获取流数据
				inputStream = conn.getInputStream();
//				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//				int results=0;
//			    while((results=reader.read())!=-1)
//			    {
//			        //因为读取到的是int类型的，所以要强制类型转换
//			        System.out.print((char)results);
//			    }
//			    reader.close();

				// 将获取流转为base64格式
				byte[] data = null;
				ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
				byte[] buff = new byte[100];
				int rc = 0;
				while ((rc = inputStream.read(buff, 0, 100)) > 0) {
					swapStream.write(buff, 0, rc);
				}
				data = swapStream.toByteArray();
				
				result = new String(Base64.getEncoder().encode(data));
//				当import java.util.Base64;无法导入时，只能在网上找找其他的jar包，写法换成下面这种
//				result = new String(Base64.encodeBase64(data));
				
				
	        }catch (Exception e) {
				System.out.println("发送 POST 请求出现异常！"+e);
				e.printStackTrace();
			}
				//使用finally块来关闭输出流、输入流
			finally{
				try{
					if(out!=null){
						out.close();
					}
					if(inputStream!=null){
						inputStream.close();
					}
					
				}
				catch(IOException ex){
					ex.printStackTrace();
				}
			}
	        return result;

		}
	
	/**
	 * 请求Get
	 * @return 
	 */
	public String httpGet(String url) {
        // 创建 HttpClient 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpGet 请求
        HttpGet httpGet = new HttpGet(url);
        // 设置长连接
        httpGet.setHeader("Connection", "keep-alive");
        // 设置代理（模拟浏览器版本）
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        // 设置 Cookie
        httpGet.setHeader("Cookie", "UM_distinctid=16442706a09352-0376059833914f-3c604504-1fa400-16442706a0b345; CNZZDATA1262458286=1603637673-1530123020-%7C1530123020; JSESSIONID=805587506F1594AE02DC45845A7216A4");

        CloseableHttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        String httpResStr = null;
        try {
            // 请求并获得响应结果
            httpResponse = httpClient.execute(httpGet);
            httpEntity = httpResponse.getEntity();
         // 输出请求结果
//         System.out.println(EntityUtils.toString(httpEntity));
         httpResStr = EntityUtils.toString(httpEntity);
            
        } catch (IOException e) {
            e.printStackTrace();
        }          
        // 无论如何必须关闭连接
        finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

		return httpResStr;
	}
	
	/**
	 * 请求POST
	 * @return 
	 */
	public String httpPost(String url,String content,String accessToken) {
		// 创建 HttpClient 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("content", content);
        
        CloseableHttpResponse httpResponse = null;
        String httpResStr = null;
        try {
            // 设置 HttpPost 参数
        	httpPost.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), ContentType.create("application/json", "utf-8")));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            // 输出请求结果
            httpResStr = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 无论如何必须关闭连接
        finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

		return httpResStr;
	}
	
	
	@RequestMapping(value = "/likeComment",method =RequestMethod.GET)
	public Map<String,Object> likeComment(
			@RequestParam("status") String status,
			@RequestParam("openid") String openid,
			@RequestParam("session_key") String sessionkey,
			@RequestParam("subject") String subject,
			@RequestParam("aid") Long aid
		) {
			Map<String,Object> result = new HashMap<String,Object>();
			System.out.println(aid);
			News article = articleService.selectById(aid, status);
			Integer like = Integer.parseInt(article.getLikeNum()) + 1;
			
			article.setLikeNum(like.toString());
			int res = articleService.saveArticle(article);
			if(res != 0) {
				result.put("artile", article);
				result.put("statusCode", 200);
				result.put("message", "成功");
			}else {
				result.put("statusCode", 400);
				result.put("message", "失败");
			}

			return result;
		}
	
	/**
     * 单文件上传 
     * @return
	 * @throws IOException 
	 * @throws QiniuException 
     */
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Map<String, Object> uploadVideo(@RequestParam("file") MultipartFile file) throws QiniuException, IOException{
        Map<String, Object> result = new HashMap<>();
        System.out.println(file.getOriginalFilename());       
        if(!file.isEmpty()) {
        	 //配置七牛云密钥
            String ACCESS_KEY = Constant.AK;  
            String SECRET_KEY = Constant.SK; 
            //要上传的空间--  
            String bucketname = Constant.bucket;
             //上传文件的路径  
            String FilePath =Constant.uploadPath; 
             //密钥配置  
             Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);  
            //创建上传对象  
            UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone0()));  
             //创建随机名字
             String originalFilename=file.getOriginalFilename();
             String mine=file.getContentType();
             System.out.println(mine);
             String newFileName="upload/"+UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
            //调用put方法来进行上传
             Response res = uploadManager.put(file.getInputStream(), newFileName, 
              auth.uploadToken(bucketname),null,null);
            //打印返回信息,200为上传成功
            
            Ret ret = res.jsonToObject(Ret.class);
            System.out.println(ret.key);
            result.put("result",FilePath+ret.key);
            result.put("statusCode",200);
            result.put("message","上传成功");
        }else {
        	result.put("statusCode",400);
            result.put("message","上传失败");
        }
 
        return result;
    }
    
    class Ret {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
    }
	
}
